package com.cetcs.kmga.dataManager.controller;

import com.alibaba.fastjson.JSONObject;
import com.cetcs.kmga.common.*;
import com.cetcs.kmga.dataManager.annotation.LogAnnotation;
import com.cetcs.kmga.dataManager.entity.dataManager.vi.AuditObjectConfigVi;
import com.cetcs.kmga.dataManager.entity.dataManager.vi.ResourceVi;
import com.cetcs.kmga.dataManager.entity.dataManager.vo.*;
import com.cetcs.kmga.dataManager.entity.global.LogLevelEnum;
import com.cetcs.kmga.dataManager.entity.global.LogTypeEnum;
import com.cetcs.kmga.dataManager.service.dataManager.DataManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 类注释
 * 数据监管
 *
 * @author yyangs
 * @version V1.0 创建时间：2017-08-30 13:40
 *          Copyright 2017 by CETC
 */
@RestController
@RequestMapping("/dataManager")
public class DataManagerController extends BaseController {

    @Autowired
    private DataManagerService dataManagerService;

    /****************
     **** 数据资源管理 **
     ***************/

    /***=============================数据资源配置=================**/


    /**
     * 数据源列表
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "获取数据源列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getDataResourceList", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getDataResourceList(@RequestParam(value = "type", required = false) Integer type) {
        try {
            Data data = new Data();
            ResourceTreeVo treeVo = null;
            if (type == null) {
                treeVo = dataManagerService.getDataResourceList(data);
            } else {
                treeVo = dataManagerService.synchronizeDataResource(data);
            }
            return this.ok(treeVo);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获得审计对象信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "获得审计对象信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getAuditObjectById/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAuditObjectById(@PathVariable("id") String id) {
        try {
            Data data = new Data();
            data.put("id", id.substring(1));
            return this.ok(dataManagerService.getAuditObjectById(data));
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 配置审计对象
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "配置审计对象", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/configureAuditObject", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse configureAuditObject(@Valid @RequestBody AuditObjectConfigVi auditObjectConfigVi, BindingResult bindingResult) {
        try {
            Data data = new Data();
            if (auditObjectConfigVi.getId() != null) {
                data.put("id", auditObjectConfigVi.getId().substring(1));
            }
            if (auditObjectConfigVi.getToId() != null) {
                data.put("resrcId", auditObjectConfigVi.getToId().substring(1));
            }
//            if(auditObjectConfigVi.getFromId()!=null){
//                data.put("id",auditObjectConfigVi.getFromId());
//            }
            if (auditObjectConfigVi.getAliases() != null) {
                data.put("alias", auditObjectConfigVi.getAliases());
                //监测是否有重名的
                Data params = new Data();
                params.put("alias",auditObjectConfigVi.getAliases());
                params.put("idF",auditObjectConfigVi.getId().substring(1));
                Integer isRepeat = 0;
                isRepeat = dataManagerService.isExitForAuditObject(params);
                if(isRepeat>0){
                    //有重名的
                    return this.error(500, "名称已存在！请改用其他名称");
                }
            }
            if (auditObjectConfigVi.getText() != null) {
                data.put("remark", auditObjectConfigVi.getText());
            }
            Integer result = dataManagerService.configureAuditObject(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(500, "修改失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 根据id获得资源信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "获取某一资源信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getResourceById/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getResourceById(@PathVariable("id") String id) {
        try {
            Data data = new Data();
            data.put("id", id.substring(1));
            return this.ok(dataManagerService.getResourceById(data));
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 新增或者修改数据源
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "新增或者修改数据源数据", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/saveOrUpdataResource", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse saveOrUpdataResource(@Valid @RequestBody ResourceVi resourceVi, BindingResult bindingResult) {
        try {
            Data data = new Data();
            data.put("id", resourceVi.getId());
            data.put("name", resourceVi.getName());
            if(resourceVi.getName()!=null) {
                Data params = new Data();
                params.put("name", resourceVi.getName());
                params.put("idF", resourceVi.getId().substring(1));
                Integer isRepeat = 0;
                isRepeat = dataManagerService.isExitForResource(params);
                if (isRepeat > 0) {
                    //有重名的
                    return this.error(500, "名称已存在！请改用其他名称");
                }
            }
            data.put("vers", resourceVi.getEdition());
            data.put("serverIp", resourceVi.getIp());
            data.put("supevLevel", resourceVi.getResourcesGrade());
            data.put("desc", resourceVi.getText());
            data.put("updateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            Integer result = dataManagerService.saveOrUpdataResource(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                if (resourceVi.getId().startsWith("A")) {
                    return this.error(500, "操作失败！请重新添加");
                } else {
                    return this.error(500, "操作失败！请再次更新");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 删除数据源
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "删除数据源", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/deleteResource/{id}", method = RequestMethod.DELETE, produces = {"application/json", "application/xml"})
    public BaseResponse deleteResource(@PathVariable("id") String id) {
        try {
            Data data = new Data();
            data.put("id", id.substring(1));
            Integer result = dataManagerService.deleteResource(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(500, "删除失败！数据不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 根据数据源获取告警规则列表  分页
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "根据数据源获取告警规则列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getSecuRuleByResourceId/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getSecuRuleByResourceId(@PathVariable("id")String id,
                                                @RequestParam(required =false,defaultValue ="-1")int grade,
                                                @RequestParam(required =false,defaultValue ="-1")int type,
                                                @RequestParam(required =false,defaultValue ="")String text,
                                                @RequestParam(required =false,defaultValue ="1")int page,
                                                @RequestParam(required =false,defaultValue ="5")int pageSize) {
        try {
            Data data = new Data();
            data.put("resrcId",id.substring(1));
            if(grade!=-1) {
                data.put("level", grade);
            }
            if(type!=-1) {
                data.put("stat", type);
            }
            if(!"".equals(text.trim())) {
                data.put("keyValue", text);
            }
            data.put("page",page);
            data.put("pageSize",pageSize);
            Page result = dataManagerService.getSecuRuleByResourceId(data);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }
    /**
     * 添加资源类型
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "新增资源类型", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getAndAddResourceType", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAndAddResourceType() {
        try {
            Data data = new Data();
            List<ResrcTypeVo> resrcTypeVos = dataManagerService.getAndAddResourceType(data);
            resrcTypeVos.sort(new Comparator<ResrcTypeVo>() {
                @Override
                public int compare(ResrcTypeVo o1, ResrcTypeVo o2) {
                    return o1.getId().compareTo(o2.getId());
                }
            });
            ResrcTypeListVo resrcTypeListVo = new ResrcTypeListVo();
            resrcTypeListVo.setContent(resrcTypeVos);
            return this.ok(resrcTypeListVo);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 修改告警规则状态
     *
     * @param id
     * @return
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "修改告警规则状态", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/updateSecuRuleByRuleId", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse updateSecuRuleByRuleId(@RequestParam(value = "id")String id,
                                               @RequestParam(value = "checked")Boolean checked) {
        try {
            Data param = new Data();
            param.put("id",id);
            //checked 如果是true表示 当前是1  应该修改为 0 反之亦然
            param.put("stat",checked==true?1:0);
            Integer result = dataManagerService.updateSecuRule(param);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }



    //==================== zhangchunlin start ======================//

    /**
     * 查询用户表
     *
     * @return
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "查询收件人用户列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/findSysUsers", method = RequestMethod.GET)
    public BaseResponse findSysUsers(@RequestParam(value = "keyword", required = false) String keyword) {
        try {
            List<Map> users = dataManagerService.findSysUsers(keyword);

            return this.ok(users);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 添加告警规则
     *
     * @param vo
     * @return
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "添加告警规则", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/addSecuRuleByResourceId", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse addIpSetting(@RequestBody JSONObject vo) {
        try {
            JSONObject secuRuleInfo = vo.getJSONObject("secuRuleInfo");
            String resourceId = (String) secuRuleInfo.get("resrcId");
            resourceId = resourceId.substring(1);
            secuRuleInfo.put("resrcId",resourceId);
            vo.put("secuRuleInfo",secuRuleInfo);

            SecuRuleAddVo param = vo.toJavaObject(SecuRuleAddVo.class);
            String checkMessage = param.checkInput();
            if (!StringUtils.isEmpty(checkMessage)) {
                return this.error(Constant.SYSTEM_EXCEPTION, checkMessage);
            }
            dataManagerService.saveSecuRuleByResourceId(param);
            return this.ok(1);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 查询数据源告警规则
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "查询数据源告警规则", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/findSecuRuleById/{id}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse findSecuRuleById(@PathVariable("id") String id) {
        try {
            JSONObject vo = dataManagerService.findSecuRuleById(id);
            return this.ok(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 根据ID删除告警规则
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "删除告警规则", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/removeSecuRuleById/{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse removeIpSettingById(@PathVariable("id") String id) {
        try {
            dataManagerService.removeSecuRuleById(id);
            return this.ok(1);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 根据ID批量删除告警规则
     */
    @LogAnnotation(module = "数据资源管理-告警管理-数据资源配置", logType = LogTypeEnum.业务日志, description = "批量删除告警规则", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/batchRemoveSecuRule", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse batchRemoveIpSetting(@RequestBody Data data) {
        try {
            List<String> ids = (List<String>) data.get("ids");
            dataManagerService.batchRemoveSecuRule(ids);
            return this.ok(1);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }
    //==================== zhangchunlin end ======================//


    /**
     * 流量阈值设置
     */

    /*
     * 流量阈值设置客户端查询
     */
    @LogAnnotation(module = "数据监管-流向分析-风险阈值设置", logType = LogTypeEnum.业务日志, description = "查看列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getClientLimitList", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse getClientLimitList(WebRequest request, @RequestParam(required =false,defaultValue ="1")int page,
                                      @RequestParam(required =false,defaultValue ="5")int pageSize) {
        try {
            Data data = getParam(request);
            Data params = new Data();
            params.put("value",data.getString("inWord"));
            params.put("page",page);
            params.put("pageSize",pageSize);
            Page result = dataManagerService.getClientLimitList(params);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(500);
        }
    }

    /*
     * 流量阈值设置客户端通过IP查询
     */
    @LogAnnotation(module = "数据监管-流向分析-风险阈值设置", logType = LogTypeEnum.业务日志, description = "查看列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getClientLimitInfoByIp", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse getClientLimitInfoByIp(WebRequest request) {
        try {
            Data data = getParam(request);
            ClientLimitInfoVo result = dataManagerService.getClientLimitInfoByIp(data);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(500);
        }
    }

    /*
     * 流量阈值设置修改阈值
     */
    @LogAnnotation(module = "数据监管-流向分析-风险阈值设置", logType = LogTypeEnum.业务日志, description = "修改阈值", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/updateClientLimit", method = RequestMethod.GET)
    public BaseResponse updateClientLimit(WebRequest request) {
        try {

            Data params = getParam(request);
            String inLeft = params.getString("inLeft");
            String inRight = params.getString("inRight");
            String outLeft = params.getString("outLeft");
            String outRight = params.getString("outRight");

            if (inLeft == null||inLeft.equals("")){
                inLeft = "0";
            }

            if (inRight == null||inRight.equals("")){
                inRight = "MAX";
            }

            if (outLeft == null||outLeft.equals("")){
                outLeft = "0";
            }

            if (outRight == null||outRight.equals("")){
                outRight = "MAX";
            }

            params.put("inLimit",inLeft+","+inRight);
            params.put("outLimit",outLeft+","+outRight);
            params.put("id",params.getString("id"));
            int result = dataManagerService.updateClientLimit(params);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(500);
        }
    }


}
